<template>
  <Screen v-if="screening" />
  <Editor v-else-if="_isPC" />
  <Mobile v-else />
</template>

<script lang="ts" setup name="MainPage">
import { useMainStore, useScreenStore, useSlidesStore, useSnapshotStore, useWikiStore } from '@/store'
import { storeToRefs } from 'pinia'
import { onMounted, onUnmounted } from 'vue'
// import { LOCALSTORAGE_KEY_DISCARDED_DB } from '@/configs/storage'
// import { deleteDiscardedDB } from '@/utils/database'
import { getDocContent, getSharedDocContent, getTemDetail } from '@/api'
import useStatusNotifier from '@/hooks/useStatusNotifier'
import { IframeViewMode } from '@/types/iframeViewMode'
import i18next from 'i18next'
import { isPC } from './utils/common'
import Editor from './views/Editor/index.vue'
import Mobile from './views/Mobile/index.vue'
import Screen from './views/Screen/index.vue'

const _isPC = isPC()

const mainStore = useMainStore()
const snapshotStore = useSnapshotStore()
// const { databaseId } = storeToRefs(mainStore)
const screenStore = useScreenStore()
const { screening } = storeToRefs(screenStore)
const { setSlides, setTitle, setTheme } = useSlidesStore()

const search = window.location.search.substring(1)
const urlSearchParams = new URLSearchParams(search)
const { setWikiInfo, setCreator, setPreview} = useWikiStore()

const wikiId = urlSearchParams.get('wikiId')
const documentId = urlSearchParams.get('documentId') ?? ''
const sharePassword = urlSearchParams.get('sharePassword')
const lang = urlSearchParams.get('lang') || 'zh'
const iframeViewMode = urlSearchParams.get('iframeViewMode') || IframeViewMode.STANDARD

const token = urlSearchParams.get('token')
if (token) window.localStorage.setItem('token_key', token)

setWikiInfo(wikiId, documentId, iframeViewMode)

// 普通文档预览、模板预览、分享 三种模式下，设置为全屏模式
if (iframeViewMode.indexOf('PREVIEW') > -1 || iframeViewMode === IframeViewMode.SHARE || iframeViewMode === IframeViewMode.PPTLINK) {
  screenStore.setScreening(true)
  setPreview(true)
}

window.localStorage.setItem('lang', lang)

if (import.meta.env.MODE !== 'development') {
  window.onbeforeunload = () => false
}

const { sendLoadedMsg, ESClistener } = useStatusNotifier()

onMounted(async () => {
  i18next.changeLanguage(lang)
  window.document.addEventListener('keydown', ESClistener)
  // await deleteDiscardedDB()
  snapshotStore.initSnapshotDatabase()
  mainStore.setAvailableFonts()
  try {
    let res
    let content
    if (documentId) {
      if (iframeViewMode.indexOf('TEMPLATE') > -1) { // 模板
        const res = await getTemDetail(documentId)
        content = JSON.parse(res.data.content)
      }
      else if (iframeViewMode === IframeViewMode.SHARE) { // 分享链接
        res = await getSharedDocContent(documentId, {sharePassword})
        content = JSON.parse(res.data.data.content) // 从 Result 对象读
      } 
      else {
        try {
          res = await getDocContent(documentId)
          content = JSON.parse(res.data.document.content) // 从 DocumentDetailVO 对象读
          setCreator(res.data.document.createUser.name)

          sendLoadedMsg(res?.data?.document?.updatedAt ?? new Date())
        } 
        catch (e) {
          console.log(e)
        }
      }
    }
    
    if (content) {
      const {slides, title, theme } = content
      // 在这里读取数据，并赋值给大菠萝里的slides,title,theme
      setSlides(slides)
      setTheme(theme)
      setTitle(title)
    }
  }
  catch (e) {
    console.error(e)
  }
})

onUnmounted(() => {
  window.document.removeEventListener('keydown', ESClistener)
})

// 应用注销时向 localStorage 中记录下本次 indexedDB 的数据库ID，用于之后清除数据库
// window.addEventListener('unload', () => {
//   const discardedDB = localStorage.getItem(LOCALSTORAGE_KEY_DISCARDED_DB)
//   const discardedDBList: string[] = discardedDB ? JSON.parse(discardedDB) : []

//   discardedDBList.push(databaseId.value)

//   const newDiscardedDB = JSON.stringify(discardedDBList)
//   localStorage.setItem(LOCALSTORAGE_KEY_DISCARDED_DB, newDiscardedDB)
// })
</script>

<style lang="scss">
#app {
  height: 100%;
}
</style>@/hooks/useStatusNotify